package com.ittao.taoaicodemother.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.ittao.taoaicodemother.constant.UserConstant;
import com.ittao.taoaicodemother.exception.BusinessException;
import com.ittao.taoaicodemother.exception.ErrorCode;
import com.ittao.taoaicodemother.exception.ThrowUtils;
import com.ittao.taoaicodemother.manage.upload.FilePictureUpload;
import com.ittao.taoaicodemother.manage.upload.PictureUploadTemplate;
import com.ittao.taoaicodemother.manage.upload.UrlPictureUpload;
import com.ittao.taoaicodemother.mapper.UserMapper;
import com.ittao.taoaicodemother.model.dto.user.UserQueryRequest;
import com.ittao.taoaicodemother.model.entity.User;
import com.ittao.taoaicodemother.model.enums.UserRoleEnum;
import com.ittao.taoaicodemother.model.vo.user.LoginUserVO;
import com.ittao.taoaicodemother.model.vo.user.UserVO;
import com.ittao.taoaicodemother.service.UserService;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户 服务层实现。
 *
 * @author <a href="https://gitee.com/it-heima-ht">程序员 Tao</a>
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private FilePictureUpload filePictureUpload;

    @Resource
    private UrlPictureUpload urlPictureUpload;

    /**
     * 用户注册
     *
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @return 新用户 id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验参数
        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }

        // 2. 智能处理用户账号重复问题（绕过逻辑删除机制）
        // 使用自定义SQL直接查询，完全绕过MyBatis-Flex的逻辑删除
        User existingUser = this.mapper.selectIgnoreLogicDelete(userAccount);

        if (existingUser != null) {
            // 如果用户已被逻辑删除，则恢复该用户账号
            if (existingUser.getIsDelete() == 1) {
                log.info("用户账号 {} 之前被删除，现在恢复注册", userAccount);

                // 3. 密码加密
                String encryptPassword = getEncryptPassword(userPassword);

                // 4. 更新用户信息，相当于重新注册
                existingUser.setUserPassword(encryptPassword);
                existingUser.setUserName(userAccount);
                existingUser.setUserRole(UserRoleEnum.USER.getValue());
                existingUser.setIsDelete(0); // 恢复用户

                // 使用自定义更新方法，绕过逻辑删除机制
                int updateResult = this.mapper.updateIgnoreLogicDelete(existingUser);
                if (updateResult == 0) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
                }
                return existingUser.getId();
            } else {
                // 如果用户未被删除，则账号重复
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号已存在");
            }
        }

        // 3. 如果用户不存在，则正常注册
        String encryptPassword = getEncryptPassword(userPassword);

        // 4. 创建用户，插入数据库
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName(userAccount);
        user.setUserRole(UserRoleEnum.USER.getValue());
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        }
        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @param request
     * @return 脱敏后的用户信息
     */
    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验参数
        if (StrUtil.hasBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }

        // 2. 对用户传递的密码进行加密
        String encryptPassword = getEncryptPassword(userPassword);

        // 3. 查询数据库中的用户是否存在
        QueryWrapper queryWrapper = QueryWrapper.create()
                .eq("userAccount", userAccount)
                .eq("userPassword", encryptPassword);
        User user = this.getOne(queryWrapper);

        // 不存在，抛异常
        if (user == null) {
            log.info("用户登录失败，账号或密码不正确");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }

        // 4. 保存用户的登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);

        return this.getLoginUserVO(user);
    }

    /**
     * 获取加密后的密码
     *
     * @param userPassword 用户密码
     * @return 加密后的密码
     */
    @Override
    public String getEncryptPassword(String userPassword) {
        // 加盐，混淆密码
        final String SALT = "tao";
        return DigestUtils.md5DigestAsHex((userPassword + SALT).getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 获取当前登录用户 - 增强版本，支持异常处理
     *
     * @param request 请求
     * @return 当前登录用户
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        User currentUser = null;
        Object userObj = null;

        try {
            // 从 Session 中获取用户信息
            userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);

            if (userObj instanceof User) {
                currentUser = (User) userObj;
            } else if (userObj instanceof LinkedHashMap) {
                // 处理序列化导致的LinkedHashMap问题
                try {
                    ObjectMapper objectMapper = new ObjectMapper();
                    // 注册Java 8时间模块，支持LocalDateTime等时间类型
                    objectMapper.registerModule(new JavaTimeModule());
                    currentUser = objectMapper.convertValue(userObj, User.class);
                } catch (Exception e) {
                    log.warn("Session 会话数据转换失败: {}", e.getMessage());
                    // 注意：这里不清除session，因为可能只是序列化格式问题，session本身是有效的
                    // 让后续逻辑判断是否真的需要重新登录
                }
            }

        } catch (Exception e) {
            log.error("获取登录用户信息时发生异常: {}", e.getMessage(), e);
            // 只有在严重异常时才清除session，避免误删有效session
            if (userObj == null) {
                try {
                    request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
                } catch (Exception cleanupException) {
                    log.warn("清理会话数据时发生异常: {}", cleanupException.getMessage());
                }
            }
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "获取用户信息失败，请重新登录");
        }

        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        // 从数据库中查询（追求性能的话可以注释掉，直接使用当前的用户对象）
        long userIdLong = currentUser.getId();
        currentUser = this.getById(userIdLong);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    /**
     * 获取登录用户信息
     *
     * @param user 用户
     * @return 脱敏后的用户信息
     */
    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtil.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    /**
     * 获取用户详细信息
     *
     * @param user 用户
     * @return 脱敏后的用户信息
     */
    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 获取用户列表
     *
     * @param userList 用户列表
     * @return 脱敏后的用户信息列表
     */
    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream()
                .map(this::getUserVO)
                .collect(Collectors.toList());
    }

    /**
     * 用户退出登录 - 增强版本
     *
     * @param request 请求
     * @return 是否登出成功
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 判断是否已经登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "未登录");
        }

        // 获取当前用户ID，处理类型转换问题
        User currentUser = null;
        Long userId = null;

        try {
            if (userObj instanceof User) {
                currentUser = (User) userObj;
            } else if (userObj instanceof LinkedHashMap) {
                // 处理JSON序列化导致的LinkedHashMap问题
                ObjectMapper objectMapper = new ObjectMapper();
                // 注册Java 8时间模块，支持LocalDateTime等时间类型
                objectMapper.registerModule(new JavaTimeModule());
                currentUser = objectMapper.convertValue(userObj, User.class);
            }

            if (currentUser != null) {
                userId = currentUser.getId();
            }
        } catch (Exception e) {
            log.warn("获取用户ID时发生异常: {}", e.getMessage());
            // 即使使获取用户ID失败，也要清理session
        }

        // 移除Session登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);

        log.info("用户 {} 已成功登出", userId);
        return true;
    }

    /**
     * 构建查询条件 - 适配MyBatis-Flex
     *
     * @param userQueryRequest 用户查询请求体
     * @return 查询条件
     */
    @Override
    public QueryWrapper getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userName = userQueryRequest.getUserName();
        String userAccount = userQueryRequest.getUserAccount();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();

        QueryWrapper queryWrapper = QueryWrapper.create();

        if (ObjUtil.isNotNull(id)) {
            queryWrapper.eq("id", id);
        }
        if (ObjUtil.isNotNull(userRole)) {
            queryWrapper.eq("userRole", userRole);
        }
        if (StrUtil.isNotBlank(userAccount)) {
            queryWrapper.like("userAccount", userAccount);
        }
        if (StrUtil.isNotBlank(userName)) {
            queryWrapper.like("userName", userName);
        }
        if (StrUtil.isNotBlank(userProfile)) {
            queryWrapper.like("userProfile", userProfile);
        }
        if (StrUtil.isNotBlank(sortField)) {
            queryWrapper.orderBy(sortField, "ascend".equals(sortOrder));
        }

        return queryWrapper;
    }

    /**
     * 修改用户密码
     *
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @param loginUser   当前登录用户
     * @return 是否修改成功
     */
    @Override
    public boolean updateUserPassword(String oldPassword, String newPassword, User loginUser) {
        // 参数校验
        if (StrUtil.hasBlank(oldPassword, newPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码不能为空");
        }
        if (newPassword.length() < 8 || newPassword.length() > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "新密码长度应为8-20位");
        }
        if (loginUser == null || loginUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        // 验证旧密码是否正确
        String encryptOldPassword = getEncryptPassword(oldPassword);
        if (!encryptOldPassword.equals(loginUser.getUserPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "旧密码不正确");
        }

        // 新密码不能与旧密码相同
        if (oldPassword.equals(newPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "新密码不能与旧密码相同");
        }

        // 加密新密码
        String encryptNewPassword = getEncryptPassword(newPassword);

        // 更新数据库中的密码
        User updateUser = new User();
        updateUser.setId(loginUser.getId());
        updateUser.setUserPassword(encryptNewPassword);

        return this.updateById(updateUser);
    }

    /**
     * 是否为管理员
     *
     * @param user 用户
     * @return 是否为管理员
     */
    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }

    /**
     * 上传用户头像
     *
     * @param inputSource 输入源，可以是文件路径、URL等
     * @param loginUser   当前登录用户
     * @return 头像URL或路径
     */
    @Override
    public String uploadPicture(Object inputSource, User loginUser) {
        // 校验参数
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);

        // 上传图片，得到图片信息
        // 根据用户 id 划分目录
        String uploadPathPrefix = String.format("user/%s", loginUser.getId());

        // 根据 inputSource 的类型判断上传方式
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
        // 返回最终上传到cos的图片地址
        return pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);
    }
}
